package jmine.tec.web.wicket.converter;

import java.io.Serializable;
import java.util.Locale;

import jmine.tec.persist.PersistMessages;
import jmine.tec.persist.naturalkey.NaturalKeyHandler;
import jmine.tec.persist.naturalkey.NaturalKeyHandlerFactory;
import jmine.tec.web.wicket.BeanReference;
import jmine.tec.web.wicket.spring.SpringBeanReference;

import org.apache.wicket.util.convert.ConversionException;
import org.apache.wicket.util.convert.IConverter;

import bancosys.tec.persist.Persistable;
import bancosys.tec.persist.dao.BaseDAO;
import bancosys.tec.persist.dao.BaseDAOFactory;
import bancosys.tec.persist.dao.BeanNotFoundException;

/**
 * @author finx
 * @created Jul 5, 2010
 */
public class NaturalKeyConverter implements IConverter {

    private final BeanReference<BaseDAOFactory> daoFactoryReference = SpringBeanReference.forType(BaseDAOFactory.class);

    private final BeanReference<NaturalKeyHandlerFactory> nkhFactoryReference = SpringBeanReference.forType(NaturalKeyHandlerFactory.class);
    
    private Class<? extends Persistable> clazz;

    /**
     * Construtor.
     * 
     * @param clazz a classe do tipo
     */
    public NaturalKeyConverter(Class<? extends Persistable> clazz) {
        this.clazz = clazz;
    }

    /**
     * {@inheritDoc}
     */
    public Object convertToObject(String value, Locale locale) {
        BaseDAO<Persistable> dao = this.daoFactoryReference.get().getGenericDAO(this.clazz);
        try {
            return dao.findByNaturalKey(value);
        } catch (BeanNotFoundException e) {
            if (value != null && value.trim().length() > 0) {
                throw new ConversionException(e);
            }
            return null;
        }
    }

    /**
     * {@inheritDoc}
     */
    public String convertToString(Object value, Locale locale) {
        NaturalKeyHandler handler = this.nkhFactoryReference.get().findNaturalKeyProperties(this.clazz);
        if (handler == null) {
            throw new ConversionException(PersistMessages.NATURAL_KEY_HANDLER_NOT_FOUND.create(value.getClass().toString()).getMessage(locale));
        }       
        Serializable nk = handler.getNaturalKey((Persistable) value);
        return nk == null ? null : nk.toString();
    }
}
